package manage.commons.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

import manage.commons.Constants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

/**
 * 邮件发送工具类
 * 
 * @author dongji
 * @since 2012-9-28 下午06:01:28
 */
public class MailUtil {
	protected static final Log logger = LogFactory.getLog(MailUtil.class);

	protected static String MAILHOSTNAME = "";// 邮件服务器地址

	/**
	 * 简单的发邮件方式 邮件内容只有标题和邮件内容 支持单个个用户批量发送
	 * 
	 * @param subject
	 * @param contents
	 * @param userEmailAddress
	 * @param fromEmailAddress
	 * @throws Exception
	 */
	public static void sendSimpleEmail(String subject, String contents,
			String userEmailAddress, String fromEmailAddress) throws Exception {
		sendSimpleEmail(subject, contents, new String[] { userEmailAddress },
				fromEmailAddress);
	}

	/**
	 * 简单的发邮件方式 邮件内容只有标题和邮件内容 支持多个用户批量发送
	 * 
	 * @param subject
	 *            邮件标题
	 * @param contents
	 *            邮件内容
	 * @param userEmailAddress
	 *            收入人的邮件地址 为数组形式
	 * @throws Exception
	 */
	public static void sendSimpleEmail(String subject, String contents,
			String[] userEmailAddress, String fromEmailAddress)
			throws Exception {
		SimpleEmail email = new SimpleEmail();
		email.setAuthenticator(new EmailAuthenticator());
		email.setHostName(MAILHOSTNAME);
		// 发送给多个人
		for (int i = 0; i < userEmailAddress.length; i++) {
			email.addTo(userEmailAddress[i], userEmailAddress[i]);
		}
		email.setFrom(fromEmailAddress, fromEmailAddress);
		email.setSubject(subject);
		email.setContent(contents, "text/plain;charset="
				+ Constants.DEFAULT_ENCODE);
		email.send();
	}

	/**
	 * 单个发送带附件给单个用户
	 * 
	 * @param subject
	 * @param contents
	 * @param userEmailAddress
	 * @param fromEmailAddress
	 * @param multiPaths
	 * @throws Exception
	 */
	public static void sendMultiPartEmail(String subject, String contents,
			String userEmailAddress, String fromEmailAddress, String multiPaths)
			throws Exception {
		sendMultiPartEmail(subject, contents,
				new String[] { userEmailAddress }, fromEmailAddress,
				new String[] { multiPaths });
	}

	/**
	 * 发送多个附件给单个用户
	 * 
	 * @param subject
	 * @param contents
	 * @param userEmailAddress
	 * @param fromEmailAddress
	 * @param multiPaths
	 * @throws Exception
	 */
	public static void sendMultiPartEmail(String subject, String contents,
			String userEmailAddress, String fromEmailAddress,
			String[] multiPaths) throws Exception {
		sendMultiPartEmail(subject, contents,
				new String[] { userEmailAddress }, fromEmailAddress, multiPaths);
	}

	/**
	 * 发送单个附件给多个用户
	 * 
	 * @param subject
	 * @param contents
	 * @param userEmailAddress
	 * @param fromEmailAddress
	 * @param multiPaths
	 * @throws Exception
	 */
	public static void sendMultiPartEmail(String subject, String contents,
			String[] userEmailAddress, String fromEmailAddress,
			String multiPaths) throws Exception {
		sendMultiPartEmail(subject, contents, userEmailAddress,
				fromEmailAddress, new String[] { multiPaths });
	}

	/**
	 * 发送带附件的邮件方式 邮件内容有标题和邮件内容和附件，附件可以是本地机器上的文本，也可以是web上的一个URL 文件，
	 * 当为web上的一个URL文件时，此方法可以将WEB中的URL文件先下载到本地，再发送给收入用户
	 * 
	 * @param subject
	 *            邮件标题
	 * @param contents
	 *            邮件内容
	 * @param userEmailAddress
	 *            收入人的邮件地址 为数组形式
	 * @param multiPaths
	 *            附件地址 为数组形式
	 * @throws Exception
	 */

	public static void sendMultiPartEmail(String subject, String contents,
			String[] userEmailAddress, String fromEmailAddress,
			String[] multiPaths) throws Exception {
		List<EmailAttachment> list = new ArrayList<EmailAttachment>();
		for (int j = 0; j < multiPaths.length; j++) {
			EmailAttachment attachment = new EmailAttachment();
			if (multiPaths[j].indexOf("http") == -1) // 判断当前这个文件路径是否在本地
														// 如果是：setPath 否则
														// setURL;
			{
				attachment.setPath(multiPaths[j]);
			} else {
				attachment.setURL(new URL(multiPaths[j]));
			}
			attachment.setDisposition(EmailAttachment.ATTACHMENT);
			attachment.setDescription("附件");
			list.add(attachment);
		}
		// 发送邮件信息
		MultiPartEmail email = new MultiPartEmail();
		email.setAuthenticator(new EmailAuthenticator());
		email.setHostName(MAILHOSTNAME);
		// 发送给多个人
		for (int i = 0; i < userEmailAddress.length; i++) {
			email.addTo(userEmailAddress[i], userEmailAddress[i]);
		}
		email.setFrom(fromEmailAddress, fromEmailAddress);
		email.setSubject(subject);
		email.setMsg(contents); // 注意这个不要使用setContent这个方法 setMsg不会出现乱码
		for (int a = 0; a < list.size(); a++) // 添加多个附件
		{
			email.attach((EmailAttachment) list.get(a));
		}
		email.send();
	}

	/**
	 * 发送Html格式的邮件
	 * 
	 * @param subject
	 *            邮件标题
	 * @param contents
	 *            邮件内容
	 * @param userEmailAddress
	 *            接收用户的邮箱地址
	 * @param fromEmailAddress
	 *            发送人的邮箱地址
	 * 
	 * @throws Exception
	 */
	public static void sendHtmlEmail(String subject, String contents,
			String[] userEmailAddress, String fromEmailAddress)
			throws Exception {
		HtmlEmail email = new HtmlEmail();
		email.setAuthenticator(new EmailAuthenticator());
		email.setHostName(MAILHOSTNAME);
		// 发送给多个人
		for (int i = 0; i < userEmailAddress.length; i++) {
			email.addTo(userEmailAddress[i], userEmailAddress[i]);
		}
		email.setFrom(fromEmailAddress, fromEmailAddress);
		email.setSubject(subject);
		email.setHtmlMsg(contents);
		email.setTextMsg(contents);
		email.send();
	}

}

/**
 * 邮件登陆授权
 * 
 */
class EmailAuthenticator extends Authenticator {
	private String username;
	private String password;

	public EmailAuthenticator() {
		Properties properties = new Properties();
		InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("email.properties");
		try {
			properties.load(inputStream);
			username = properties.getProperty("mail.username");
			password = properties.getProperty("mail.password");
			MailUtil.MAILHOSTNAME = properties.getProperty("mail.hostname");
		} catch (IOException e) {
			MailUtil.logger.error("加载邮件配置文件出错，请检查email.properties文件配置是否正确！！！！");
		}
	}

	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password);
	}
}
